package com.common.frame.utils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 操作文件相关的工具类
 */
public class FileUtils {

    public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

    public static void scanFile(String path, String format){
        MediaScannerConnection.scanFile(AppGlobals.getApplication(), new String[]{path}, new String[]{format}, null);
    }

    public static String getTypePath(String type){
        File file = AppGlobals.getApplication().getExternalFilesDir(type);
        if (!file.exists()){
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    public static String getExternalSavePath(String fileName){
        return getExternalSavePath() + File.separator + fileName;
    }

    public static String getExternalSavePath(){
        return Environment.getExternalStoragePublicDirectory("JY_IMAGE").getAbsolutePath();
    }

    /**
     * 递归删除目录/文件0
     */
    public static void deleteDir(File dir) {
        if (!dir.exists() || !dir.isDirectory()) {
            dir.delete();
            return;
        }

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDir(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    /**
     * 递归删除目录/文件
     */
    public static void deleteDir(String path) {
        deleteDir(new File(path));
    }


    /**
     * 根据文件路径获取文件Uri
     */
    public static Uri getFileUriByPath(String path) {
        return Uri.fromFile(new File(path));
    }


    public static Uri getFileUriByPathToN(File file) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //判读版本是否在7.0以上
            return FileProvider.getUriForFile(AppGlobals.getApplication(),
                    AppGlobals.getApplication().getPackageName() + ".fileprovider", file);
        }else{
            return Uri.fromFile(file);
        }
    }

    /**
     * 根据文件Uri获取路径
     */
    public static String getFilePathByUri(Uri uri) {
        String filePath = "";
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            filePath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = AppGlobals.getApplication().getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        filePath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return filePath;
    }

    /**
     * 保存图片
     */
    public static boolean saveBitmap(Bitmap bitmap, String savePath) {
        File saveFile = new File(savePath);
        createFile(saveFile.getParentFile());
        try {
            if (!saveFile.exists()){
                saveFile.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(saveFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    public static void createFile(File file){
        if (!file.exists()){
            file.mkdirs();
        }
    }

    public static File createFile(String filePath) throws IOException {
        File saveFile = new File(filePath);
        if (saveFile.isDirectory()){
            if (!saveFile.exists()){
                saveFile.mkdirs();
            }
        }else{
            if (!saveFile.getParentFile().exists()){
                saveFile.getParentFile().mkdirs();
            }
            if (saveFile.exists()){
                saveFile.delete();
            }
            saveFile.createNewFile();
        }
        return saveFile;
    }

}
